<template>
   <div class="login-container">
<van-nav-bar class="page-nav" title="登录">
  <van-icon slot="left" name="cross" @click="$router.back()" />
</van-nav-bar>
<van-form @submit="onSubmit" ref="loginForm">
  <van-field
  v-model="user.mobile"
  type="number"
  name="mobile"
    placeholder="请输入手机号"
    :rules="userFormRulers.mobile"
  >
  <i slot='left-icon' class="toutiao toutiao-yanzhengma"></i>
  </van-field>
  <van-field
  v-model="user.code"
    type="number"
    name="code"
    placeholder="请输入验证码"
    :rules="userFormRulers.code"
  >
  <i slot='left-icon' class="toutiao toutiao-shouji"></i>
   <template #button>
     <van-count-down :time="1000 * 5" format="ss s" v-if="isCountDowmShow" @finish = 'isCountDowmShow = false'/>
    <van-button size="small" type="primary" class="send-sms-btn"  native-type="button" @click="onSendSms" v-else>发送验证码</van-button>
  </template>
   </van-field>
  <div class="login-btn-wrap">
    <van-button block type="info" native-type="submit" class="login-btn">登录</van-button>
  </div>
</van-form>
  </div>
</template>

<script>
import { login, getSmsCode } from '@/api/user.js'
export default {
  data () {
    return {
      isCountDowmShow: false,
      user: {
        mobile: '',
        code: ''
      },
      userFormRulers: {
        mobile: [{ required: true, message: '手机号不能为空' },
          { pattern: /^1[3|5|7|8]\d{9}$/ }],
        code: [{ required: true, message: '验证码不能为空' },
          { pattern: /^\d{6}$/ }]
      }
    }
  },
  methods: {
    async onSubmit () {
      const user = this.user
      this.$toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 0
      })
      try {
        const res = await login(user)
        this.$store.commit('setUser', res.data.data)
        this.$toast.success('登录成功')
        console.log('登录成功', res)
      } catch (err) {
        if (err.response.status === 400) {
          this.$toast.fail('手机号或验证码错误')
          console.log('手机号或验证码错误')
        }
        this.$toast.fail('登录失败')
        console.log('登录失败', err)
      }
    },
    async onSendSms () {
      try {
        await this.$refs.loginForm.validate('mobile')
      } catch (err) {
        return console.log('验证失败', err)
      }
      this.isCountDowmShow = true
      try {
        await getSmsCode(this.user.mobile)
        console.log(777)
        this.$toast('发送成功')
        this.isCountDowmShow = false
      } catch (err) {
        if (err.response.status === 429) {
          this.$toast('发送太频繁')
        } else {
          this.$toast('发送失败，请稍后再试')
        }
      }
    }
  }
}
</script>
<style scoped lang="less">
.login-container {
  .toutiao {
    font-size: 37px;
  }
  .send-sms-btn {
    width: 170px;
    height: 46px;
    line-height: 46px;
    background-color: #ededed;
    font-size: 22px;
    color: #666;
  }
  .login-btn-wrap {
    padding: 53px 33px;
    .login-btn {
      background-color: #6db4fb;
      border: none;
    }
  }
}
</style>
